#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>

int main()
{
    // 创建共享内存
    key_t key = ftok(".", 's');
    int shmid = shmget(key, 1024, IPC_CREAT | 0666);
    if (shmid == -1)
    {
        perror("shmget");
        exit(EXIT_FAILURE);
    }
    // 将共享内存映射到进程地址空间
    char* shmaddr = (char*)shmat(shmid, NULL, 0);
    if (shmaddr == (char*)-1)
    {
        perror("shmat");
        exit(EXIT_FAILURE);
    }
    // 写入共享内存
    sprintf(shmaddr, "进入shared memory!");
    // 等待另一个进程读取共享内存内容
    sleep(5);
    // 打印共享内存内容
    printf("Shared memory: %s\n", shmaddr);
    // 解除映射
    if (shmdt(shmaddr) == -1)
    {
        perror("shmdt");
        exit(EXIT_FAILURE);
    }
    // 删除共享内存
    if (shmctl(shmid, IPC_RMID, NULL) == -1)
    {
        perror("shmctl IPC_RMID");
        exit(EXIT_FAILURE);
    }
    return 0;
}